package org.hank.compose_yyzs.ui.screen

import android.annotation.SuppressLint
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.google.gson.Gson
import com.orhanobut.logger.Logger
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.result.NavResult
import com.ramcosta.composedestinations.result.ResultRecipient
import com.ramcosta.composedestinations.result.getOr
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.bean.ProjectTreeNode
import org.hank.compose_yyzs.constants.Constants
import org.hank.compose_yyzs.bean.HomeProjectBean
import org.hank.compose_yyzs.ui.destinations.BuildingScreenDestination
import org.hank.compose_yyzs.ui.destinations.SearchScreenDestination
import org.hank.compose_yyzs.ui.paging.RefreshList
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.ui.theme.blue3
import org.hank.compose_yyzs.ui.theme.blue4
import org.hank.compose_yyzs.ui.theme.cyan4
import org.hank.compose_yyzs.ui.theme.dark8
import org.hank.compose_yyzs.ui.theme.green3
import org.hank.compose_yyzs.ui.theme.green8
import org.hank.compose_yyzs.ui.theme.half_yellow9
import org.hank.compose_yyzs.ui.theme.yellow9
import org.hank.compose_yyzs.ui.widget.EmptyCompose
import org.hank.compose_yyzs.ui.widget.clickNoWave
import org.hank.compose_yyzs.utils.getString
import org.hank.compose_yyzs.utils.getStringArray
import org.hank.compose_yyzs.viewmodel.ProjectViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/6/2 16:58
 *描述:
 */

@SuppressLint("SuspiciousIndentation")
@OptIn(ExperimentalFoundationApi::class)
@Destination
@Composable
fun ProjectScreen(
    navigation: DestinationsNavigator,
    modifier: Modifier = Modifier,
    resultRecip: ResultRecipient<SearchScreenDestination, String>
) {
    var pagers = listOf(
        getString(resourceId = R.string.all),
        getString(resourceId = R.string.complete),
        getString(resourceId = R.string.progress),
    )

    var viewModel: ProjectViewModel = hiltViewModel()
    var scope = rememberCoroutineScope()
    val projectNameState by viewModel.projectName.collectAsStateWithLifecycle()
    val areaNameState by viewModel.areaName.collectAsStateWithLifecycle()
    var pagerAll = viewModel.pagerAll.collectAsLazyPagingItems()
    var pagerComplete = viewModel.pagerComplete.collectAsLazyPagingItems()
    var pagerProgress = viewModel.pagerProgress.collectAsLazyPagingItems()
    var pagerState =
        rememberPagerState(initialPage = 0, initialPageOffsetFraction = 0f) { pagers.size }
    var lifecycleOwner = LocalLifecycleOwner.current

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { obs, event ->
            if (event == Lifecycle.Event.ON_CREATE) {
                viewModel.getProjectTree()
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    var state1 = rememberLazyGridState()
    var state2 = rememberLazyGridState()
    var state3 = rememberLazyGridState()
    var isRefreshingAll = viewModel.isRefreshingAll.collectAsStateWithLifecycle()
    var isRefreshingComplete = viewModel.isRefreshingComplete.collectAsStateWithLifecycle()
    var isRefreshingProgress = viewModel.isRefreshingProgress.collectAsStateWithLifecycle()

    Box(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = modifier
                .fillMaxSize()
        ) {
            Surface(shadowElevation = 5.dp) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(color = AppTheme.colors.mainColor)
                        .padding(8.dp)
                ) {
                    Column(
                        modifier = Modifier
                            .align(Alignment.Center),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = projectNameState,
                            style = MaterialTheme.typography.titleLarge
                        )
                        Text(
                            text = areaNameState,
                            style = MaterialTheme.typography.titleSmall.copy(color = AppTheme.colors.themeUi)
                        )
                    }

                    Image(
                        painter = painterResource(id = R.mipmap.ic_search),
                        contentDescription = "",
                        modifier = Modifier
                            .align(
                                Alignment.CenterEnd
                            )
                            .clickable(
                                onClick = {
                                    scope.launch {
                                        if (viewModel.checkProjectTree())
                                            navigation.navigate(SearchScreenDestination.route)
                                        else {
                                            //没有查询到树结构
                                            Logger.d("tree null")
                                        }
                                    }

                                },
                                indication = null,
                                interactionSource = remember { MutableInteractionSource() })
                            .padding(end = 16.dp)
                    )
                }
            }

            Text(
                text = getString(resourceId = R.string.home_project),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)
            )

            TabRow(
                selectedTabIndex = pagerState.currentPage,
                modifier = Modifier.fillMaxWidth(),
                containerColor = AppTheme.colors.mainColor
            ) {
                pagers.forEachIndexed { index, s ->
                    Tab(
                        text = {
                            Text(
                                text = s,
                                style = MaterialTheme.typography.bodyMedium.copy(
                                    color = AppTheme.colors.textPrimary,
                                    fontWeight = FontWeight.Medium
                                )
                            )
                        }, selected = pagerState.currentPage == index, onClick = {
                            when (index) {
                                0 -> {
                                    if (!isRefreshingAll.value)
                                        scope.launch {
                                            pagerState.animateScrollToPage(index)
                                        }
                                }

                                1 -> {
                                    if (!isRefreshingComplete.value)
                                        scope.launch {
                                            pagerState.animateScrollToPage(index)
                                        }
                                }

                                2 -> {
                                    if (!isRefreshingProgress.value)
                                        scope.launch {
                                            pagerState.animateScrollToPage(index)
                                        }
                                }
                            }
                        })
                }
            }

            HorizontalPager(
                state = pagerState,
                userScrollEnabled = false,
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .padding(16.dp)
            ) { index ->
                if (pagerState.currentPage == index) {
                    var pager: LazyPagingItems<HomeProjectBean>? = null
                    when (index) {
                        0 -> {
                            pager = pagerAll
                        }

                        1 -> {
                            pager = pagerComplete
                        }

                        2 -> {
                            pager = pagerProgress
                        }
                    }
                    LaunchedEffect(key1 = null) {
                        var currentDeptId = MMKV.defaultMMKV().getLong(Constants.DEPTID, 0L)
                        when (index) {
                            0 -> {
                                if (viewModel.lastDeptIdAll.value != currentDeptId) {
                                    delay(100)
                                    pagerAll.refresh()
                                }
                            }

                            1 -> {
                                if (viewModel.lastDeptIdComplete.value != currentDeptId) {
                                    delay(100)
                                    pagerComplete.refresh()
                                }
                            }

                            2 -> {
                                if (viewModel.lastDeptIdPregress.value != currentDeptId) {
                                    delay(100)
                                   pagerProgress.refresh()
                                }
                            }
                        }
                    }
                    Box(modifier = Modifier.fillMaxSize()) {
                        if (pager!!.itemCount == 0 && pager.loadState.append !is LoadState.Error)
                            EmptyCompose()
                        RefreshList(
                            lazyPagingItems = pager!!,
                            isRefreshing = if (index == 0) isRefreshingAll.value else if (index == 1) isRefreshingComplete.value else isRefreshingProgress.value,
                            onRefresh = {
                                scope.launch {
                                    when (index) {
                                        0 -> {
                                            viewModel.isRefreshingAll.emit(true)
                                        }

                                        1 -> {
                                            viewModel.isRefreshingComplete.emit(true)
                                        }

                                        2 -> {
                                            viewModel.isRefreshingProgress.emit(true)
                                        }
                                    }
                                }
                            },
                            listState = if (index == 0) state1 else if (index == 1) state2 else if (index == 2) state3 else state1
                        ) {
                            items(
                                pager!!.itemCount,
                                key = pager.itemKey { it -> it.id }) { item ->
                                ListItemProjectCompose(pager[item]!!) {
                                    MMKV.defaultMMKV().putString(
                                        Constants.CURRENT_PROJECT_NAME,
                                        pager[item]?.projectName
                                    )
                                    navigation.navigate(
                                        BuildingScreenDestination(
                                            pager[item]?.id ?: -1
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    resultRecip.onNavResult { result ->
        when (result) {
            is NavResult.Canceled -> {
                //没有选择项目
                Logger.d("project empty")
            }

            else -> {
                //选择了项目。
                var project: String = result.getOr { "" }
                Logger.d("get project $project")
                MMKV.defaultMMKV().putString(Constants.CURRENT_PROJECTTREE, project)
                var selectProjectTree = Gson().fromJson(project, ProjectTreeNode::class.java)
                MMKV.defaultMMKV().putLong(
                    Constants.DEPTID,
                    selectProjectTree.id
                )

                scope.launch {
                    delay(100)
                    viewModel.projectName.emit(selectProjectTree.name)
                    viewModel.areaName.emit(selectProjectTree.areaName!!)
                    Logger.d("currentPage = ${pagerState.currentPage}")
                    when (pagerState.currentPage) {
                        0 ->
                            pagerAll.refresh()

                        1 ->
                            pagerComplete.refresh()

                        2 ->
                            pagerProgress.refresh()
                    }
                }
            }
        }
    }
}

@Composable
private fun ListItemProjectCompose(projectBean: HomeProjectBean, onProjectClick: () -> Unit) {
    Surface(
        shape = MaterialTheme.shapes.medium,
        color = AppTheme.colors.mainColor,
        shadowElevation = 1.dp,
    ) {
        Box(modifier = Modifier
            .drawBehind {
                val path = Path().apply {
                    moveTo(0f, 0f)
                    lineTo(0f, 96.dp.value)
                    lineTo(96.dp.value, 0f)
                    close()
                }

                drawPath(
                    path = path,
                    color = half_yellow9
                )
            }
            .clickNoWave {
                onProjectClick.invoke()
            }
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
            ) {
                Row {
                    Image(
                        painter = painterResource(
                            id = when (projectBean.status) {
                                0 ->
                                    R.mipmap.ic_status_complete

                                1 ->
                                    R.mipmap.ic_status_progress

                                else ->
                                    R.mipmap.ic_status_waiting
                            }
                        ),
                        contentDescription = ""
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = when (projectBean.status) {
                            0 ->
                                getString(resourceId = R.string.complete)

                            1 ->
                                getString(resourceId = R.string.progress)

                            else ->
                                getString(resourceId = R.string.unstart)
                        }, style = MaterialTheme.typography.bodyMedium.copy(
                            color = when (projectBean.status) {
                                0 ->
                                    green3

                                1 ->
                                    yellow9

                                else ->
                                    dark8
                            }
                        )
                    )
                }
                Text(text = projectBean.projectName)
                Text(
                    text = getString(resourceId = R.string.task_num),
                    style = MaterialTheme.typography.bodySmall
                )
                projectBean.totalData?.forEach { item ->
                    StageItemCompose(
                        if (item.stageType == 0) 1 else item.stageType,
                        item.finishRoomCount,
                        item.totalRoomCount
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                }
            }
        }
    }

}

/**
 * 项目下多阶段item显示。
 * @param stageType 阶段NUM
 * @param finishCount 已完成数量
 * @param totalCount 总数量
 */
@Composable
private fun StageItemCompose(stageType: Int, finishCount: Int, totalCount: Int) {
    var stageName = getStringArray(resourceId = R.array.home_stage_show)
    var localColor = when (stageType) {
        1 -> blue3
        2 -> yellow9
        3 -> cyan4
        4 -> blue4
        5 -> green8
        else -> blue3
    }
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text(text = stageName[stageType - 1], style = MaterialTheme.typography.labelSmall)
        Spacer(modifier = Modifier.width(4.dp))
        Box(
            modifier = Modifier
                .weight(1f)
                .height(intrinsicSize = IntrinsicSize.Max)
                .background(shape = MaterialTheme.shapes.large, color = AppTheme.colors.secondBtnBg)
                .drawBehind {
                    drawRoundRect(
                        color = localColor,
                        size = Size(
                            size.width * (finishCount.toFloat() / totalCount.toFloat()),
                            size.height
                        ),
                        cornerRadius = CornerRadius(24.dp.toPx())
                    )
                }
        ) {
            Text(text = "", style = MaterialTheme.typography.labelSmall.copy(fontSize = 5.sp))
        }
        Spacer(modifier = Modifier.width(4.dp))
        Text(
            text = "$finishCount/$totalCount", style = MaterialTheme.typography.labelSmall.copy(
                color = localColor
            )
        )
    }
}

@Preview(showBackground = true)
@Composable
fun MyItemPrev() {
    AppTheme {
        Surface(
            modifier = Modifier
                .fillMaxSize()
                .statusBarsPadding()
                .background(color = AppTheme.colors.mainColor)
        ) {
            Column {
                StageItemCompose(4, finishCount = 22, totalCount = 25)
            }
        }
    }
}